package encaps.action;

import encaps.entities.Grant;
import encaps.resources.Config;
import encaps.utils.LogViewer;
import encaps.utils.StringUtil;
import encaps.utils.SystemException;
import org.jdom.Element;

public class ViewLogAction extends Action {

    public static final int RECORDS_PER_PAGE = 5;
    public static final String PAGE = "page";
    public static final String VIEW_LOG = "viewLog";
    public static final String ENTITY_TYPE = "Log";
    private ActionContext actionContext;
    private static final LogViewer logViewer = new LogViewer();

    public ViewLogAction(ActionContext context, Grant requiredGrant) {
        this.actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            int pageNumber = getPageNumber();
            int recordsPerPage = Config.getRecordsPerPage();
            int fromRecord = (pageNumber - 1) * recordsPerPage;
            return logViewer.getResult(pageNumber, recordsPerPage, fromRecord, actionContext.getUserRole());
        } catch (SystemException e) {
            throw new ActionExecutionException(e);
        }
    }

    private int getPageNumber() throws SystemException {
        String pageParameter = actionContext.getTextParameter(PAGE);
        int page;
        if (StringUtil.isEmpty(pageParameter)) {
            page = 1;
        } else {
            page = Integer.parseInt(pageParameter);
        }
        return page;
    }
}
